<?php
// +----------------------------------------------------------------------
// | 有理想的地方，地狱都是天堂。
// +----------------------------------------------------------------------
// | Copyright @ df81.com 版权所有
// +----------------------------------------------------------------------
// | 作者: 南国老符 邮箱：1062129401@qq.com
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\admin\model\Area as areaModel;
use app\admin\model\Language as languageModel;
use app\admin\validate\Config as configValidate;
use think\exception\ValidateException;
use think\facade\Config as configFacade;
use think\facade\Db;
use think\facade\View;

class Config extends Base{
    public function index(){
        // 加载前端配置文件
        $langConfig = app()->getBasePath().$this->lang.DS.'config'.DS.'template.php';
        configFacade::load($langConfig);
        
        // 城市分站
        $default_lang = config('lang.default_lang'); $default_domain = ''; $domainBindArray = config('app.domain_bind');
        $cityList = Db::name('area')->where('is_domain',1)->where('lang',$default_lang)->field('id,urlroute,bind_domain')->select();
        // 默认语言绑定的域名
        if(!empty($domainBindArray)){
            $bindDomainArray = array_keys($domainBindArray,$default_lang);
            foreach ($cityList as $cityRs){
                if(!empty($cityRs['bind_domain'])){
                    foreach ($bindDomainArray as $k => $domain){
                        if($cityRs['bind_domain'] == $domain) unset($bindDomainArray[$k]);
                    }
                }
            }
            foreach ($bindDomainArray as $k => $domain){
                if(substr_count($domain,'.') == 1) unset($bindDomainArray[$k]);
            }
            $bindDomainArray = array_values($bindDomainArray);
            $default_domain = $bindDomainArray[0];
        }
        View::assign('default_domain',$default_domain);
            
        if(!request()->isPost()){
            // 启用的模型
            $moduleWhere[] = ['lang','=',$this->lang]; $moduleWhere[] = ['disabled','=',1];
            $moduleList = Db::name('module')->where($moduleWhere)->order('sequence desc')->select();
            View::assign('moduleList',$moduleList);

            $env = '';
            if(is_file(app()->getRootPath().'.env')) $env = app()->getRootPath().'.env';
            View::assign('env',$env);
            
            // 语言列表
            $langList = languageModel::index(1);
            View::assign('langList',$langList);
            
            return view();
        }else{
            // 非域名访问情况下，不可绑定域名
            $domainStr = "/^(?:[A-za-z0-9-]+\.)+[A-za-z]{2,4}(?:[\/\?#][\/=\?%\-&~`@[\]\':+!\.#\w]*)?$/";  
            if((input('bind_lang') == 1 or input('city_site') == 1) and !preg_match($domainStr,request()->host(true))){
                return json(['code' => 1001, 'msg' => '请先给本站绑定域名', 'data' => array('domain'=>request()->host(true))]);
            }
            
            //判断参数设置是否开启了参数设置
            // if(config('app.isdisplay.parameter') != 1) return json(lang('c_parameter_enable_first'));

            // 表单验证
            try {
                validate(configValidate::class)->check(input('post.'));
            } catch (ValidateException $e) {
                return json(['code' => 1002, 'msg' => $e->getMessage(), 'data' => '']);
            }

            //显示设置
            $site_array = input('site/a');
            $site = empty($site_array) ? 0 : $site_array[0];
            $field_array = input('field/a');
            $field = empty($field_array) ? 0 : $field_array[0];
            $chat_array = input('chat/a');
            $chat = empty($chat_array) ? 0 : $chat_array[0];
            $ad_array = input('ad/a');
            $ad = empty($ad_array) ? 0 : $ad_array[0];
            $keyword_array = input('keyword/a');
            $keyword = empty($keyword_array) ? 0 : $keyword_array[0];
            $navigation_array = input('navigation/a');
            $navigation = empty($navigation_array) ? 0 : $navigation_array[0];
            $area_array = input('area/a');
            $area = empty($area_array) ? 0 : $area_array[0];
            $module_array = input('module/a');
            $module = empty($module_array) ? 0 : $module_array[0];
            $filemanage_array = input('filemanage/a');
            $filemanage = empty($filemanage_array) ? 0 : $filemanage_array[0];
            $showmodule_array = input('showmodule/a');
            $showmodule = empty($showmodule_array) ? 0 : $showmodule_array[0];
            $typeattribute_array = input('typeattribute/a');
            $typeattribute = empty($typeattribute_array) ? 0 : $typeattribute_array[0];

            $parameter_array = input('parameter/a');
            $parameter = empty($parameter_array) ? 0 : $parameter_array[0];
            $databackup_array = input('databackup/a');
            $databackup = empty($databackup_array) ? 0 : $databackup_array[0];
            $language_array = input('language/a');
            $language = empty($language_array) ? 0 : $language_array[0];
            $templatemanage_array = input('templatemanage/a');
            $templatemanage = empty($templatemanage_array) ? 0 : $templatemanage_array[0];
            $authgroup_array = input('authgroup/a');
            $authgroup = empty($authgroup_array) ? 0 : $authgroup_array[0];
            $authrule_array = input('authrule/a');
            $authrule = empty($authrule_array) ? 0 : $authrule_array[0];
            $uniapp_array = input('uniapp/a');
            $uniapp = empty($uniapp_array) ? 0 : $uniapp_array[0];

            $shop_set_array = input('shop_set/a');
            $shop_set = empty($shop_set_array) ? 0 : $shop_set_array[0];
            $social_array = input('social/a');
            $social = empty($social_array) ? 0 : $social_array[0];
            $email_array = input('email/a');
            $email = empty($email_array) ? 0 : $email_array[0];
            $sms_array = input('sms/a');
            $sms = empty($sms_array) ? 0 : $sms_array[0];
            $payment_array = input('payment/a');
            $payment = empty($payment_array) ? 0 : $payment_array[0];

            $isdisplay_array = input('isdisplay/a');
            $display_feedback = in_array('feedback', $isdisplay_array) ? 1 : 0;

            $user_array = input('user/a');
            $user = empty($user_array) ? 0 : $user_array[0];
            $shop_order_array = input('shop_order/a');
            $shop_order = empty($shop_order_array) ? 0 : $shop_order_array[0];
            $shop_tax_array = input('shop_tax/a');
            $shop_tax = empty($shop_tax_array) ? 0 : $shop_tax_array[0];
            $shop_coupon_array = input('shop_coupon/a');
            $shop_coupon = empty($shop_coupon_array) ? 0 : $shop_coupon_array[0];
            $comment_array = input('comment/a');
            $comment = empty($comment_array) ? 0 : $comment_array[0];

            //前端启用验证码的模块
            $captcha_array = input('captcha/a');
            $captcha_feedback = in_array('feedback', $captcha_array) ? 1 : 0;
            $captcha_user = in_array('user', $captcha_array) ? 1 : 0;

            $baidu_ak = input('baidu_ak');
            if($baidu_ak == '******') $baidu_ak = config('app.other.baidu_ak');

            // $wechat_array = input('wechat/a');
            // $wechat = empty($wechat_array) ? 0 : $wechat_array[0];
            // $alipay_array = input('alipay/a');
            // $alipay = empty($alipay_array) ? 0 : $alipay_array[0];
            
            $str = "<?php
            //配置文件
            return [
                //显示设置
                'isdisplay' => [
                    'site' => ".$site.",
                    'field' => ".$field.",
                    'chat' => ".$chat.",
                    'ad' => ".$ad.",
                    'keyword' => ".$keyword.",
                    'navigation' => ".$navigation.",
                    'area' => ".$area.",
                    'module' => ".$module.",
                    'filemanage' => ".$filemanage.",
                    'showmodule' => ".$showmodule.",
                    'typeattribute' => ".$typeattribute.",

                    'parameter' => ".$parameter.",
                    'databackup' => ".$databackup.",
                    'language' => ".$language.",
                    'templatemanage' => ".$templatemanage.",
                    'authgroup' => ".$authgroup.",
                    'authrule' => ".$authrule.",
                    'uniapp' => ".$uniapp.",

                    'shop_set' => ".$shop_set.",
                    'social' => ".$social.",
                    'email' => ".$email.",
                    'sms' => ".$sms.",
                    'payment' => ".$payment.",

                    'feedback' => ".$display_feedback.",
                    'user' => ".$user.",
                    'shop_order' => ".$shop_order.",
                    'shop_tax' => ".$shop_tax.",
                    'shop_coupon' => ".$shop_coupon.",
                    'comment' => ".$comment.",
                    
                ],

                //前端启用验证码的模块
                'captcha' => [
                    'feedback' => ".$captcha_feedback.",
                    'user' => ".$captcha_user.",
                ],

                //数据库备份还原设置
                'dataconfig' => [
                    'path'     => '../databak/',//数据库备份路径
                    'part'     => '20971520',//数据库备份卷大小，20M
                    'compress' => '".input('compress')."',//数据库备份文件是否启用压缩 0不压缩 1 压缩
                    'level'    => '9', //数据库备份文件压缩级别 1普通 4 一般  9最高
                ],

                //其他设置
                'other' => [
                    'baidu_ak' => '".$baidu_ak."',
                    'suffix' => 'com/api',
                    'deletefile' => '".input('deletefile')."',
                    'no_delete_fieldid' => '".input('no_delete_fieldid')."',
                    'no_delete_attid' => '".input('no_delete_attid')."',
                    'no_delete_areaid' => '".input('no_delete_areaid')."',
                    'no_delete_sendtemplateid' => '".input('no_delete_sendtemplateid')."',
                    'no_delete_authgroupid' => '".input('no_delete_authgroupid')."',
                    'system_type' => '".input('system_type')."',
                ],

            ];";
            $configFile = app()->getAppPath().'config'.DS.'app.php';
            $appFile = app()->getConfigPath().'app.php';
            $globalConfigPath = app()->getConfigPath().'global.php';

            $rootPath = app()->getRootPath();
            /*判断文件和文件夹是否有写入权限 开始*/
            /*
            $cannot_write_txt = lang('c_file_cannot_write');
            if(isWritable($configFile) == false){
                $error_tips = $configFile.'<br>'.$cannot_write_txt;
                return json($error_tips);
            }
            if(isWritable($rootPath) == false){
                $error_tips = $rootPath.'<br>'.$cannot_write_txt;
                return json($error_tips);
            }
            if(isWritable($appFile) == false){
                $error_tips = $appFile.'<br>'.$cannot_write_txt;
                return json($error_tips);
            }
            if(isWritable($globalConfigPath) == false){
                $error_tips = $globalConfigPath.'<br>'.$cannot_write_txt;
                return json($error_tips);
            }
            */
            /*判断文件和文件夹是否有写入权限 结束*/

            $result = file_put_contents($configFile,$str);
            /*修改总配置文件的调试模式 开始*/
            // 删除环境文件.env
            $env = $rootPath.'.env';
            if(file_exists($env) and is_writable(app()->getRootPath())){
                unlink($env);
            }
            if(input('app_debug') == 'true'){
                $oldFile = '\'exception_tmpl\'   => app()->getBasePath() . \'think_exception.html\',';
                $newFile = '\'exception_tmpl\'   => app()->getThinkPath() . \'tpl/think_exception.tpl\',';
                // 写入环境文件.env
                if (is_writable(app()->getRootPath())) {
                    $envFile = fopen($env, "w");
                    $envTxt = "APP_DEBUG = true\n\n";
                    // $envTxt .= "[APP]\n";
                    // $envTxt .= "DEFAULT_TIMEZONE = Asia/Shanghai\n\n";
                    // $envTxt .= "[DATABASE]\n";
                    // $envTxt .= "TYPE = mysql\n";
                    // $envTxt .= "HOSTNAME = ".config('database.connections.mysql.hostname')."\n";
                    // $envTxt .= "DATABASE = ".config('database.connections.mysql.database')."\n";
                    // $envTxt .= "USERNAME = ".config('database.connections.mysql.username')."\n";
                    // $envTxt .= "PASSWORD = ".config('database.connections.mysql.password')."\n";
                    // $envTxt .= "HOSTPORT = 3306\n";
                    // $envTxt .= "CHARSET = utf8\n";
                    // $envTxt .= "DEBUG = true\n\n";
                    // $envTxt .= "[LANG]\n";
                    fwrite($envFile, $envTxt);
                    fclose($envFile);
                }
            }else{
                $oldFile = '\'exception_tmpl\'   => app()->getThinkPath() . \'tpl/think_exception.tpl\',';
                $newFile = '\'exception_tmpl\'   => app()->getBasePath() . \'think_exception.html\',';
            }
            $dofile = new \common\Dofile();
            //修改报错模板参数
            $dofile->editFile($appFile,$oldFile,$newFile);
            /*修改绑定域名 开始*/
            // 旧的绑定
            $new_domain_bind = $old_domain_bind = ''; $configDomainArray = array();
            if(!empty($domainBindArray)){
                foreach ($domainBindArray as $bindDomain => $bindLang){
                    $old_domain_bind .= '\''.$bindDomain.'\'=>\''.$bindLang.'\',';
                    $configDomainArray[] = $bindDomain;
                }
                $old_domain_bind = '\'domain_bind\'      => ['.rtrim($old_domain_bind,',').']';
            }else{
                $old_domain_bind = '\'domain_bind\'      => []';
            }
            // 新的绑定
            $bindUrlArray = input('bind_url/a'); $bindMuluArray = input('bind_mulu/a');
            foreach ($bindUrlArray as $bindKey => $bindUrl){
                $new_domain_bind .= '\''.$bindUrl.'\'=>\''.$bindMuluArray[$bindKey].'\',';
            }
            
            /*城市分站 开始*/
            $bind_lang = input('bind_lang'); $areaList = array();
            $city_site = empty($bind_lang) ? 0 : input('city_site');
            if(!empty($city_site)){
                /*批量启用城市分站 开始*/
                $rootDomain = request()->rootDomain();
                foreach ($cityList as $cityRs){
                    // 城市绑定
                    if(!empty($cityRs['bind_domain'])){
                        $new_domain_bind .= '\''.$cityRs['bind_domain'].'\'=>\''.$default_lang.'\',';
                    }else{
                        if(!empty($cityRs['urlroute'])){
                            $new_domain_bind .= '\''.$cityRs['urlroute'].'.'.$rootDomain.'\'=>\''.$default_lang.'\',';
                            
                            // 城市绑定，更新area数据表
                            $areaList[] = array('id'=>$cityRs['id'],'bind_domain'=>$cityRs['urlroute'].'.'.$rootDomain);
                        }
                    }
                }
                // 城市绑定，更新area数据表
                if(!empty($areaList)){
                    $areaModule = new areaModel;
                    $areaModule->saveAll($areaList);
                }
                /*批量启用城市分站 结束*/
            }
            /*城市分站 结束*/
            
            // 绑定根域名到默认语言
            $new_domain_bind = '\'domain_bind\'      => ['.rtrim($new_domain_bind,',').']';
            // 判断是否绑定
            if(input('bind_lang') == 0) $new_domain_bind = '\'domain_bind\'      => []';
            $dofile->editFile($appFile,$old_domain_bind,$new_domain_bind);
            // 修改导航表
            if(input('bind_lang') != config('global.url.bind_lang')){
                $navList = Db::name('navigation')->select();
                $navData = array();
                foreach ($navList as $navRs){
                    // 链接地址，不绑定二级域名
                    if(empty(input('bind_lang')) and stripos($navRs['linkurl'],'/'.$navRs['lang'].'/') === false){
                        // 首页
                        $linkurl = rtrim($navRs['linkurl'],'/');
                        $linkurl = str_replace('http://','',$linkurl);
                        $linkurl = str_replace('https://','',$linkurl);
                        if(in_array($linkurl,$configDomainArray)){
                            $langRs = Db::name('language')->where('mulu',$navRs['lang'])->field('isdefault')->find();
                            if($langRs['isdefault'] == 1){
                                $linkurl = '/';
                            }else{
                                $linkurl = '/'.$navRs['lang'].'/';
                            }
                        }else{
                            $linkurl = '/'.$navRs['lang'].$navRs['linkurl'];
                        }
                    }else{
                        // 首页
                        if($navRs['linkurl'] == '/'.$navRs['lang'].'/' or $navRs['linkurl'] == '/' or strpos($navRs['linkurl'],'http') !== false){
                            if(!empty($domainBindArray)){
                                foreach ($domainBindArray as $bindDomain => $bindLang){
                                    if($bindLang == $navRs['lang']) $linkurl = request()->scheme().'://'.$bindDomain.'/';
                                }
                                // 默认语言绑定的域名
                                if($navRs['lang'] == $default_lang) $linkurl = request()->scheme().'://'.$default_domain.'/';
                            }else{
                                foreach ($bindMuluArray as $bindKey => $bindLang){
                                    if($bindLang == $navRs['lang']) $linkurl = request()->scheme().'://'.$bindUrlArray[$bindKey].'/';
                                }
                            }
                        }else{
                            $linkurl = str_replace('/'.$navRs['lang'].'/','/',$navRs['linkurl']);
                        }
                    }
                    Db::name('navigation')->where('id',$navRs['id'])->update(['linkurl'=>$linkurl]);
                }
            }
            /*修改绑定域名 结束*/
            /*修改总配置文件的调试模式 结束*/
            /*修改 前后端共用配置 开始*/
            $bind_lang = input('bind_lang');
            $city_site = empty($bind_lang) ? 0 : input('city_site');
            if(stripos(input('salt'),'**') !== false){
                $salt = config('global.salt');
            }else{
                $salt = input('salt');
            }
            $globalNewContent = "<?php
            //前后端共用配置
            return [
                //系统版本
                'version' => [
                    // 版本名称
                    'name' => '".config('global.version.name')."',
                    // 版本号
                    'code' => '".config('global.version.code')."',
                ],
                
                //登录失败设置
                'verify_times' => '".input('verify_times')."',
                'lock_times' => '".input('lock_times')."',
                'lock_minute' => '".input('lock_minute')."',
                // ip黑名单
                'ip_black' =>'".input('ip_black')."',
                // 加密盐值
                'salt' => '".$salt."',

                // URL模式
                'url' => [
                    'city_site' => '".$city_site."',
                    'bind_lang' => '".$bind_lang."',
                    'view' => '".input('url_view')."',
                    'root' => '".input('url_root')."',
                    'root_module' => '".input('url_root_module')."',
                    'root_type' => '".input('url_root_type')."',
                    'category' => '".input('url_category')."',
                    'length' => '".input('url_length')."',
                    'pinyin_type' => '".input('pinyin_type')."',
                ],

                // 存储模式
                'storage' => [
                    'type' => '".config('global.storage.type')."',
                    'imageMaxSize' => '".config('global.storage.imageMaxSize')."',
                    'fileMaxSize' => '".config('global.storage.fileMaxSize')."',
                    'upload_filename' => '".config('global.storage.upload_filename')."',
                ],

                // 图片水印等
                'image' => [
                    'thumbnail' => '".config('global.image.thumbnail')."',
                    'thumbwidth' => '".config('global.image.thumbwidth')."',
                    'thumbheight' => '".config('global.image.thumbheight')."',
                    'thumb' => '".config('global.image.thumb')."',
                    'water' => '".config('global.image.water')."',
                    'waterPosition' => '".config('global.image.waterPosition')."',
                    'waterImage' => '".config('global.image.waterImage')."',
                    'transparency' => '".config('global.image.transparency')."',
                    'waterText' => '".config('global.image.waterText')."',
                    'waterfont' => '".config('global.image.waterfont')."',
                    'watercolor' => '".config('global.image.watercolor')."',
                    'watersize' => '".config('global.image.watersize')."',
                ],
            ];";
            
            $dofile->editFile($globalConfigPath,file_get_contents($globalConfigPath),$globalNewContent);
            /*修改 前后端共用配置 结束*/

            /*修改前端配置文件：留言必填项 开始*/
            $feedback_array = input('feedback/a');
            $realname = in_array('realname', $feedback_array) ? 1 : 0;
            $mobile = in_array('mobile', $feedback_array) ? 1 : 0;
            $email = in_array('email', $feedback_array) ? 1 : 0;
            $telephone = in_array('telephone', $feedback_array) ? 1 : 0;
            $content = in_array('content', $feedback_array) ? 1 : 0;

            if(file_exists($langConfig)){
                $oldFeedback = '\'realname\' => '.config('feedback.realname').',\'mobile\' => '.config('feedback.mobile').',\'email\' => '.config('feedback.email').',\'telephone\' => '.config('feedback.telephone').',\'content\' => '.config('feedback.content').',';
                $newFeedback = '\'realname\' => '.$realname.',\'mobile\' => '.$mobile.',\'email\' => '.$email.',\'telephone\' => '.$telephone.',\'content\' => '.$content.',';
                $dofile->editFile($langConfig,$oldFeedback,$newFeedback);
            }
            /*修改前端配置文件：留言必填项 结束*/

            /*解决cookie跨域*/
            // $oldCookieDomain = '\'domain\'    => \''.config('cookie.domain').'\'';
            // if($bind_lang == 1){
            //     $newCookieDomain = '\'domain\'    => \''.request()->rootDomain().'\'';
            // }else{
            //     $newCookieDomain = '\'domain\'    => \'\'';
            // }
            // $dofile->editFile(config_path().'cookie.php',$oldCookieDomain,$newCookieDomain);

            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
        }
    }
}